package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.Gjjutil.Base64Utils;
import com.block.datapush.service.apipush.utils.Gjjutil.RSAUtils;
import com.block.datapush.service.apipush.utils.GongjijinUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 86   信狐 51公积金
 */
@Service
public class GongjiJinPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = StrUtil.format(pushApiKeyParam.getCheckUrl(), pushApiKeyParam.getApiCode());
        String phone = memberSourceInfo.getMobileMd5();
        String idcard = SecureUtil.md5(memberSourceInfo.getIdcard()).toLowerCase();

        Map<Object, Object> bizMap = new HashMap<>();
        bizMap.put("phone_md5", phone);
        bizMap.put("idno_md5", idcard);
        bizMap.put("gender", memberSourceInfo.getSex() == 1 ? "男" : "女");
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("working_city", memberSourceInfo.getProvince() +"/"+ memberSourceInfo.getCity());
        bizMap.put("gjj", GongjijinUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("shebao", GongjijinUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("house", GongjijinUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicle", GongjijinUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("zhima_score",GongjijinUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("insurance",GongjijinUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("occupation",GongjijinUtil.getprofession(memberSourceInfo.getGongzuo()));
        bizMap.put("business_license",99);
        bizMap.put("company_years",99);
        bizMap.put("education",GongjijinUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("credit",99);
        bizMap.put("credit_record",GongjijinUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("loan_situation",99);
        bizMap.put("monthly_salary",GongjijinUtil.getshouru(memberSourceInfo.getShouru()));
        bizMap.put("salary_type",1);
        bizMap.put("loan_amount",GongjijinUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loan_period",GongjijinUtil.getloanPerod(memberSourceInfo.getLoanTime()));
        bizMap.put("loan_purpose",GongjijinUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("ip", memberSourceInfo.getReqIp());


        String jsonString = JSON.toJSONString(bizMap);

        PublicKey publicKey = RSAUtils.loadPublicKey(pushApiKeyParam.getPubKey());
        byte[] encryptByte = RSAUtils.encryptData(jsonString.getBytes("utf-8"), publicKey);
        String content = Base64Utils.encode(encryptByte);

        // 从字符串中得到私钥
        PrivateKey privateKey = RSAUtils.loadPrivateKey(pushApiKeyParam.getPriKey());
        // 加签
        String signStr = RSAUtils.rsaSign(encryptByte, privateKey);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content",content);
        paramMap.put("sign",signStr);

        log.info("【51公积金】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        String content1 = resultObject.getString("content");

        byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(content1), privateKey);
        String decryptStr = new String(decryptByte);

        log.info("【51公积金】撞库结束【result】{}", decryptStr);

        JSONObject resultObject1 = JSON.parseObject(decryptStr);
        String code = resultObject1.getString("code");
        String msg = resultObject1.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            String serialNo = resultObject1.getString("serial_no");
            extJson.put("serialNo", serialNo);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setOutOrderNo(serialNo);
            return pushApiResult;
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String serialNo = extJson.getString("serialNo");

        String requestUrl = StrUtil.format(pushApiKeyParam.getRegisterUrl(), pushApiKeyParam.getApiCode());;

        Map<Object, Object> bizMap = new HashMap<>();
        bizMap.put("serial_no", serialNo);
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("idno", memberSourceInfo.getIdcard());
        bizMap.put("is_authorize", 1);
        String nowDateStr = LocalDateUtil.getNowDateStrByTotalDataTime();
        bizMap.put("authorize_time", nowDateStr);

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String jumpUrl = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());
        bizMap.put("redirect_url", jumpUrl);

        String jsonString = JSON.toJSONString(bizMap);

        PublicKey publicKey = RSAUtils.loadPublicKey(pushApiKeyParam.getPubKey());
        byte[] encryptByte = RSAUtils.encryptData(jsonString.getBytes("utf-8"), publicKey);
        String content = Base64Utils.encode(encryptByte);

        // 从字符串中得到私钥
        PrivateKey privateKey = RSAUtils.loadPrivateKey(pushApiKeyParam.getPriKey());
        // 加签
        String signStr = RSAUtils.rsaSign(encryptByte, privateKey);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content",content);
        paramMap.put("sign",signStr);

        log.info("【51公积金】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);
        String content1 = resultObject.getString("content");

        byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(content1), privateKey);
        String decryptStr = new String(decryptByte);

        log.info("【51公积金】导单结束【result】{}", decryptStr);

        JSONObject resultObject1 = JSON.parseObject(decryptStr);
        String code = resultObject1.getString("code");
        String msg = resultObject1.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            String skipUrl = resultObject1.getString("skip_url");
            pushApiResult.setApproveUrl(skipUrl);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.WAIT_QUERY.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());

        String requestUrl = StrUtil.format(pushApiKeyParam.getQueryUrl(), pushApiKeyParam.getApiCode());

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone_md5", SecureUtil.md5(pushQueryParam.getMobile()).toLowerCase());
        bizMap.put("date", LocalDate.now().toString());

        String jsonString = JSON.toJSONString(bizMap);
        PublicKey publicKey = RSAUtils.loadPublicKey(pushApiKeyParam.getPubKey());
        byte[] encryptByte = RSAUtils.encryptData(jsonString.getBytes("utf-8"), publicKey);
        String content = Base64Utils.encode(encryptByte);

        // 从字符串中得到私钥
        PrivateKey privateKey = RSAUtils.loadPrivateKey(pushApiKeyParam.getPriKey());
        // 加签
        String signStr = RSAUtils.rsaSign(encryptByte, privateKey);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content",content);
        paramMap.put("sign",signStr);

        log.info("【51公积金】查询开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);

        String content1 = resultObject.getString("content");

        byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(content1), privateKey);
        String decryptStr = new String(decryptByte);

        log.info("【51公积金】查询结束【result】{}", decryptStr);

        JSONObject resultObject1 = JSON.parseObject(decryptStr);
        String code = resultObject1.getString("code");
        String msg = resultObject1.getString("msg");
        String time = resultObject1.getString("time");


        pushApiResult.setCode(code + "|" + msg+ "|"+ time );
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }


    public static void main(String[] args) {

        String contentInfo = "{\"sign\":\"Z/2Ooz+WR/tVDCqrV5VWWE+Q1fxXNQek/UUl+OKLS4FhmulCnKzGcBUAVrnUIsr/m3FR+/JANjte6eSstj5RxnARoHFNqHHBmTxXXTFyHzO/7tJNVq8Uqdm36+kRWTEZECWZbNY7t0IsYJmKIbASBkUL/Y1+kNgIXbGR8IvGKE854mXHD2fE+IlTw8sUdOJq7dKCSvpM0giCwqe2PWMfJzDSn65INXdSem8c0heuKjih0Kf138PTFeRuDqLdeF6xIAe6RZOBhb/94DCFSPtBkoopESwmAYOVvFdOI1a1WTGuf4eFQtGPp1IdB4DL9+g/8J1vGAqqpZoGm+bmMYMBXw==\",\"content\":\"D9qYpotyYSh9w4G80afuOxHLmi97a2Ss8ArCEd93onH0AOu1o/bb62Ar8GHFjN/I/lrw12eRMkGK9tc/maIbuCjBgrDm9E69Du/KUEOci4SKImiP2p47TXTVIs3RM3LwumDtM0I+8T2O3XekiS8GPjvikqRx81ksgBsMzjKm5zmP70ysUWLzGNK2naxlK/cXfHHvur1bAMs989i27LoEfmvNKCntRfBpKWvZXKmKNV7fXpRtqfeViQ5ArhLsXIinRdnOTFierG6qBZFsIIauXN92EyltQVUQJQF5paeau9OEmkSQGdYYofzdXKzFSfnNTgeLBSAM7A5kNMH1dmkqTpyuffpVBwoKeRVAjXzMeNwoWHMsJKS8y/60MbWH708xBJvwdIyFr5PlxpnXYJVuK0tP9GbTR/E9LZfEuKlwavzynFYoeOCHPH7upseek7gcqTQnI82IWndKM//nMlAK4rTSbHiETEbpnIzCjPEPL8UbfR4ebMHnqfQXWcoEOKbPttewdg7ZmkWzAEfZiQN5DQItZnOhKcAiu53TRg/i13KqLDyHg2xXZv+udyqqFozR1Xusv53pdSD5UqG7e+DeorkTgG/gm19vWNxn5thP+qfpKkiz0HHSWgbTITw1+c6qbgWcmcdTJTrjqVuJMop9yMno3lo8nkTENuaumiIIx+k=\"}";

        JSONObject jsonObject = JSON.parseObject(contentInfo);
        String content = jsonObject.getString("content");




    }
}
